package workspan

import (
    "fmt"
    "strconv"
)

func SpawnParallelWorkTree(workA, workB, degree, span int) {
    fmt.Println("Spawning a parallel work tree with params:",
                workA,
                workB,
                degree,
                span)
    wait := make(chan bool)
    go ParallelWorker(workA, workB, degree, 0, span, wait, "root")
    <-wait
}

func ParallelWorker(workA, workB, children, depth, span int, resp chan bool, myID string) {
    //fmt.Println("Before split, worker did work=", workA, "depth=", depth)
    //fmt.Println(myID, " checking in.")

    // Spawn children
    if (depth < span) {
        wait := make(chan bool, children)
        for i := 0; i < children; i++ {
            //fmt.Println("Spawning ", children, "children at depth=", depth+1)
            child_ID := myID + "-" + strconv.Itoa(i)
            go ParallelWorker(workA, workB, children, depth+1, span, wait, child_ID)
        }

        for i := 0; i < children; i++ {
            <-wait
        }
        //fmt.Println("After split, worker did work=", workB)
    }

    resp <- true
}
